<template>
  <div class="wrapper">
    <header>
      <!-- 跳转设置 -->
      <li @click="goToIndex" class="back-button">
        <img class="icon" :src="'src/img/left.png'" alt="返回图标">
      </li>
      <i class="fa fa-angle-left" onclick="history.go(-1)"></i>
      <p>注册</p>
      <div></div>
    </header>
    <div class="top-ban"></div>
    <h1>欢迎注册</h1>
    <table>
      <tr>
        <td>手机号码</td>
        <td>
          <input type="text" v-model="state.users.userId" placeholder="请输入手机号码" @blur="checkPhoneNumber">
        </td>
      </tr>
      <!-- <tr>
        <td>输入验证码</td>
        <td>
          <input type="text" v-model="state.verification.verificationCode" placeholder="输入验证码" :disabled="!phoneNumberEntered">
          <button :disabled="!state.verification.canSend" @click="sendVerificationCode">{{ sendCodeText }}</button>
        </td>
      </tr> -->
      <tr>
        <td>真实姓名</td>
        <td><input type="text" v-model="state.users.realName" placeholder="真实姓名便于查看体检报告"></td>
      </tr>
      <tr>
        <td>生日</td>
        <td><input type="date" v-model="state.users.birthday"></td>
      </tr>
      <tr>
        <td>性别</td>
        <td>
          <input type="radio" id="male" value="1" v-model="state.users.sex">
          <label for="male">男</label>
          <input type="radio" id="female" value="0" v-model="state.users.sex">
          <label for="female">女</label>
        </td>
      </tr>
      <tr>
        <td>身份证号</td>
        <td><input type="text" v-model="state.users.identityCard" placeholder="请输入身份证号"></td>
      </tr>
      <tr>
        <td>密码</td>
        <td><input type="password" v-model="state.users.password" placeholder="请输入密码"></td>
      </tr>
      <tr>
        <td>确认密码</td>
        <td><input type="password" v-model="state.password2" placeholder="请再次输入密码"></td>
      </tr>
    </table>
    <div class="btn" @click="finish">完成</div>
  </div>
</template>

<script>
import { reactive, toRefs, ref, onMounted, onUnmounted, computed } from "vue";
import { useRouter } from "vue-router";

import axios from "axios";
axios.defaults.baseURL = "http://localhost:8080/";

export default {
  setup() {
    const router = useRouter();
    const phoneNumberEntered = ref(false);
    const intervalId = ref(null); // 存储倒计时的interval ID

    const state = reactive({
      users: {
        userId: '',
        password: '',//真正传给后端的密码
        realName: '',
        birthday: '',
        sex: '',
        identityCard: '',
        userType: 1,
      },
      password2: '',//再次确认的密码

      verification: {
        verificationCode: '',
        canSend: true, // 控制发送验证码按钮的状态
        countdown: 60, // 倒计时时间
      },
    });

    //验证码逻辑
    // 检查手机号是否输入
    const checkPhoneNumber = () => {
      if (state.users.userId) {
        phoneNumberEntered.value = true;
      } else {
        phoneNumberEntered.value = false;
      }
    };

    // 发送验证码
    const sendVerificationCode = async () => {
      if (!phoneNumberEntered.value) {
        alert("请输入手机号码！");
        return;
      }
      if (!state.verification.canSend) return; // 防止重复点击
      state.verification.canSend = false;

      try {
        await axios.post("http://localhost:8080/code/sendCode", { phone: state.users.userId });
        startCountdown();
      } catch (error) {
        console.error("发送验证码失败:", error);
        alert("发送验证码失败，请稍后重试。");
      }
    };

    // 倒计时逻辑
    const startCountdown = () => {
      intervalId.value = setInterval(() => {
        if (state.verification.countdown > 0) {
          state.verification.countdown -= 1;
        } else {
          clearInterval(intervalId.value);
          state.verification.canSend = true;
          state.verification.countdown = 60;
        }
      }, 1000);
    };

    // 停止倒计时（例如在切换登录方式或页面离开时）
    const stopCountdown = () => {
      if (intervalId.value) {
        clearInterval(intervalId.value);
        intervalId.value = null;
      }
    };
    function goToIndex() {
      router.push('/');
    }
    function finish() {
      //表单验证
      if (state.users.userId == '') {
        alert('手机号码不能为空！');
        return;
      }
      if (state.users.password == '') {
        alert('密码不能为空！');
        return;
      }
      if (state.users.realName == '') {
        alert('真实姓名不能为空！');
        return;
      }
      if (state.users.identityCard == '') {
        alert('身份证号不能为空！');
        return;
      }
      // if(state.users.identityCard.length != 18){
      //   alert('身份证号格式不正确！');
      //   return;
      // }
      if (state.users.password != state.password2) {
        alert('两次密码不一致！');
        return;
      }
      if (state.users.sex == '') {
        alert('请选择性别！');
        return;
      }

      console.log(state.users);
      //注册
      axios.post('http://localhost:8080/users/register', state.users)  //json
        .then((response) => {
          if (response.data.code == 200) {
            alert('注册成功！');
            router.push('/');
          } else if (response.data.code == 600) {
            alert('账户已存在');
          } else {
            alert(response.data.msg);
          }
        })
        .catch((error) => {
          console.error(error);
        })
    }

    // 清除interval（例如在组件卸载时）
    onMounted(() => stopCountdown);
    onUnmounted(() => stopCountdown);

    // 计算属性处理发送验证码按钮文本
    const sendCodeText = computed(() => {
      return state.verification.canSend ? "发送验证码" : `重新发送(${state.verification.countdown}s)`;
    });

    return {
      ...toRefs(state),
      finish,
      goToIndex,
      phoneNumberEntered,
      sendVerificationCode,
      sendCodeText,
      checkPhoneNumber,
      state, // 添加这一行来将 `state` 对象暴露给模板
    };
  },
};
</script>



<style scoped>
/*********************** 总容器 ***********************/
.wrapper {
  width: 100%;
  height: 100%;
}

/*********************** header ***********************/
header {
  width: 100%;
  height: 15.7vw;
  background-color: #FFF;

  position: fixed;
  left: 0;
  top: 0;

  display: flex;
  align-items: center;
  justify-content: space-between;

  box-sizing: border-box;
  padding: 0 3.6vw;
}

header .fa {
  font-size: 8vw;
}

/*********************** 标题部分 ***********************/
h1 {
  font-size: 7.4vw;
  font-weight: 500;
  box-sizing: border-box;
  padding: 0 3.6vw;
  margin-top: 6vw;
}

/*********************** common样式 ***********************/
.top-ban {
  width: 100%;
  height: 15.7vw;
}

/*********************** table ***********************/
table {
  width: 92.8vw;
  margin: 0 auto;
  margin-top: 5vw;
  border-collapse: collapse;

  font-size: 4.2vw;
}

table tr td {
  height: 12vw;
  border-bottom: solid 1px #DDD;
}

table tr td input {
  border: none;
  outline: none;
}

/*********************** btn ***********************/
.btn {
  width: 92.8vw;
  margin: 0 auto;
  height: 12vw;
  margin-top: 8vw;
  background-color: #137E92;
  border-radius: 2vw;
  color: #FFF;
  font-size: 5vw;
  text-align: center;
  line-height: 12vw;

  user-select: none;
  cursor: pointer;
}



/* 跳转设置 */
.icon {
  float: left;

  width: 50%;
  height: 8.2vw;
}
</style>